package com.lp.guoguo.service.impl;

import com.lp.guoguo.service.QuartzJobService;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * 定时任务服务实现类
 */
@Service
public class QuartzJobServiceImpl implements QuartzJobService {
    
    private static final Logger log = LoggerFactory.getLogger(QuartzJobServiceImpl.class);
    
    @Autowired
    private Scheduler scheduler;
    
    @Override
    public void addJob(String jobClassName, String jobName, String jobGroupName, String cronExpression, Map<String, Object> jobData) throws Exception {
        // 构建job信息
        Class<? extends Job> jobClass = (Class<? extends Job>) Class.forName(jobClassName);
        JobDetail jobDetail = JobBuilder.newJob(jobClass)
                .withIdentity(jobName, jobGroupName)
                .build();
        
        // 设置job参数
        if (jobData != null && jobData.size() > 0) {
            jobDetail.getJobDataMap().putAll(jobData);
        }
        
        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        
        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(jobName, jobGroupName)
                .withSchedule(scheduleBuilder)
                .build();
        
        // 交给调度器调度
        scheduler.scheduleJob(jobDetail, trigger);
        
        // 如果设置为已暂停状态，则暂停任务
        if (scheduler.isShutdown()) {
            scheduler.start();
        }
        
        log.info("创建定时任务成功: {} - {}", jobGroupName, jobName);
    }
    
    @Override
    public void pauseJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.pauseJob(JobKey.jobKey(jobName, jobGroupName));
        log.info("暂停定时任务: {} - {}", jobGroupName, jobName);
    }
    
    @Override
    public void resumeJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.resumeJob(JobKey.jobKey(jobName, jobGroupName));
        log.info("恢复定时任务: {} - {}", jobGroupName, jobName);
    }
    
    @Override
    public void updateJobCron(String jobName, String jobGroupName, String cronExpression) throws SchedulerException {
        TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroupName);
        
        // 检查任务是否存在
        if (!scheduler.checkExists(triggerKey)) {
            throw new SchedulerException("找不到要更新的任务触发器: " + jobName);
        }
        
        CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (trigger == null) {
            throw new SchedulerException("任务触发器不是 CronTrigger 类型: " + jobName);
        }
        
        // 检查 cron 表达式是否有效
        try {
            new CronExpression(cronExpression);
        } catch (Exception e) {
            throw new SchedulerException("无效的 Cron 表达式: " + cronExpression);
        }
        
        // 表达式调度构建器
        CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cronExpression);
        
        // 按新的cronExpression表达式重新构建trigger
        trigger = trigger.getTriggerBuilder()
                .withIdentity(triggerKey)
                .withSchedule(scheduleBuilder)
                .build();
        
        // 按新的trigger重新设置job执行
        scheduler.rescheduleJob(triggerKey, trigger);
        
        log.info("更新定时任务cron表达式成功: {} - {} - {}", jobGroupName, jobName, cronExpression);
    }
    
    @Override
    public void deleteJob(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.pauseTrigger(TriggerKey.triggerKey(jobName, jobGroupName));
        scheduler.unscheduleJob(TriggerKey.triggerKey(jobName, jobGroupName));
        scheduler.deleteJob(JobKey.jobKey(jobName, jobGroupName));
        
        log.info("删除定时任务: {} - {}", jobGroupName, jobName);
    }
    
    @Override
    public void runJobNow(String jobName, String jobGroupName) throws SchedulerException {
        scheduler.triggerJob(JobKey.jobKey(jobName, jobGroupName));
        log.info("立即执行定时任务: {} - {}", jobGroupName, jobName);
    }
    
    @Override
    public boolean checkJobExists(String jobName, String jobGroupName) throws SchedulerException {
        return scheduler.checkExists(JobKey.jobKey(jobName, jobGroupName));
    }
} 